package com.xyy.saas.payment.common;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * Builder模式
 * @author dake
 * @date 20200329
 */
public class Builder<T> {
    private final Supplier<T> supplier;
    private List<Consumer<T>> modifiers = Lists.newArrayList();

    private Builder(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public static <T> Builder<T> of(Supplier<T> instantiate) {
        return new Builder<>(instantiate);
    }

    public <P> Builder<T> with(Consumer1<T, P> consumer, P p) {
        Consumer<T> c = instance -> consumer.accpect(instance, p);
        modifiers.add(c);
        return this;
    }


    public T build() {
        T t = supplier.get();
        modifiers.forEach(c -> c.accept(t));
        modifiers.clear();
        return t;
    }

    public interface Consumer1<T, P> {
        void accpect(T t, P p);
    }
}
